package Kastelic_Smitran;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLBuild {
	DocumentBuilderFactory fact;
	DocumentBuilder parser;
	Document doc;
	Element stranke, oseba, ime, priimek, racuni, racun, znesek, naziv, idRacun;
	
	public XMLBuild() {
		try{
			fact= DocumentBuilderFactory.newInstance();
			parser= fact.newDocumentBuilder();
			doc = parser.newDocument();
			stranke = doc.createElement("stranke");
			doc.appendChild(stranke);	
		}
		catch (ParserConfigurationException e) {
			// TODO: handle exception
		}
	}
	
	public XMLBuild(String ime1, String priimek1) {
		this();
		kreirajNovoOsebo(ime1, priimek1);
	}
	public XMLBuild(String imeF){
		try {
			doc = parser.parse(new File(imeF));
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("File" + imeF + " ne obstaja!");
			e.printStackTrace();
		}
	}
	public XMLBuild(String ime1, String priimek1, int idRacun1, double znesek1) {
		this();
		kreirajNovoOsebo(ime1, priimek1);	
		spremeniStanjeRacuna(ime1, idRacun1, znesek1);
	}
	
	private void kreirajNovoOsebo(String ime1,String priimek1){
		
		oseba = doc.createElement("oseba");
		ime = doc.createElement("ime");
		priimek = doc.createElement("priimek");
		racuni = doc.createElement("racuni");

		oseba.appendChild(ime);
		oseba.appendChild(priimek);
		oseba.appendChild(racuni);
		
		ime.appendChild(doc.createTextNode(ime1));
		priimek.appendChild(doc.createTextNode(priimek1));
		
		stranke.appendChild(oseba);
	}
	
	
	private void kreirajNovRacun(String oseba, String naziv1){
		
		NodeList str = stranke.getChildNodes();
		int idR = -1;
		Element os=null;
		
		for(int i = 0; i < str.getLength(); i++){
			os = (Element)str.item(i); //stranke(oseba)
			if(os.getFirstChild().getTextContent().equals(oseba)){ //ime osebe
				if(os.getLastChild().getChildNodes().getLength()>0)//racuni
					idR = Integer.parseInt(os.getLastChild().getLastChild().getFirstChild().getTextContent()) + 1;
				else
					idR = 0;
				break;
			}
		}
		if(os == null){
			System.out.println("Nobena oseba ni kreirana!");
			return;
		}
		if(idR == -1){
			System.out.println("Ta oseba ne obstaja!");
			return;
		}
		Element racun = doc.createElement("racun");
		Element naziv = doc.createElement("naziv");
		Element znesek = doc.createElement("znesek");
		Element idRacun = doc.createElement("idRacun");
		racun.appendChild(idRacun);
		racun.appendChild(naziv);			
		racun.appendChild(znesek);
		os.getLastChild().appendChild(racun);
		naziv.appendChild(doc.createTextNode(naziv1));
		znesek.appendChild(doc.createTextNode("0"));	
		idRacun.appendChild(doc.createTextNode(Integer.toString(idR)));
	}
	
	private void spremeniStanjeRacuna(String ime1, int idR, double znesek){		
		//NodeList osebeL = o
		NodeList str = stranke.getChildNodes();

		Element os=null;
		for(int i = 0; i < str.getLength(); i++){
			os = (Element) str.item(i); //stranke(oseba)
			if(os.getFirstChild().getTextContent().equals(ime1)){ //oseba		
				NodeList nl = os.getLastChild().getChildNodes();
				for(int j = 0; j < nl.getLength(); j++){//racuni
					if(nl.item(j).getFirstChild().getTextContent().equals(Integer.toString(idR))){
						double znesekS = znesek + Double.parseDouble(nl.item(i).getLastChild().getTextContent());
						nl.item(i).getLastChild().setTextContent(Double.toString(znesekS));
						return;
					}
				}			
			}
		}
		System.out.println("Stranka "+ ime1 + " in/ali racun " + idR + " ne obstaja!");
	}

	public String toString(){
		return buildXML(doc);
	}
	
	public String izpisiRacuneStranke(String ime1){
		String s;
		Element os=null;
		NodeList str = stranke.getChildNodes();
		for(int i = 0; i < str.getLength(); i++){
			os = (Element) str.item(i); //stranke(oseba)
			if(os.getFirstChild().getTextContent().equals(ime1)){ //oseba	
				s="";
				NodeList nl = os.getElementsByTagName("racun");//.getLastChild().getChildNodes();
				for(int j = 0; j < nl.getLength(); j++){ //racuni
					Element el=(Element)nl.item(j);
					s += "racID = " +  el.getElementsByTagName("idRacun").item(0).getTextContent();
					s += "\nnaziv = " + el.getElementsByTagName("naziv").item(0).getTextContent();
					s += "\nznesek = " + el.getElementsByTagName("znesek").item(0).getTextContent();
					s += "\n---\n";		
				}
				if(!s.equals(""))
					return s;
				else
					return "Stranka " + ime1 + " se nima odprtega nobenega racuna!";
			}
		}
		return "Stranka " + ime1 + " ne obstaja!";
	}
	
	public String izpisiRacunStranke(String ime1, int idR){
		String s = "Stranka " + ime1 + " ne obstaja!";
		Element os=null;
		NodeList str = stranke.getChildNodes();
		for(int i = 0; i < str.getLength(); i++){
			os = (Element) str.item(i); //stranke(oseba)
			if(os.getFirstChild().getTextContent().equals(ime1)){ //oseba	
				s="";
				
				NodeList nl = os.getLastChild().getChildNodes();
				for(int j = 0; j < nl.getLength(); j++){ //racuni
					if(nl.item(j).getFirstChild().getTextContent().equals(Integer.toString(idR))){
						NodeList racun = nl.item(j).getChildNodes();
						s += "racID = " +  racun.item(0).getTextContent();
						s += "\nnaziv = " + racun.item(1).getTextContent();
						s += "\nznesek = " + racun.item(2).getTextContent();
						s += "\n---\n";	
						return s;
					}
				}
			}
		}
		return s;
	}
	
	private void writeXML(String imeF){
		
		try {
			//BufferedWriter out = new BufferedWriter(new FileWriter(new File(imeF)));
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(imeF)), "UTF-8"));
		    out.write(buildXML(doc));
		    //Close the output stream
		    out.close();
		    System.out.println("Datoteka shranjena!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("Datoteka ni bila shranjena!");
			e.printStackTrace();
		}
	    

	}
	
	public static void main(String[] args) {
		
		XMLBuild xml = new XMLBuild("Bostjan","Kasta");
		xml.kreirajNovoOsebo("Anja", "Kastelic");
		System.out.println(xml);
		xml.kreirajNovRacun("Bostjan", "VISA");
		System.out.println(xml);
		xml.kreirajNovRacun("Bostjan", "NLB");
		System.out.println(xml);
		xml.spremeniStanjeRacuna("Bostjan", 2, 20);
		System.out.println(xml);
		System.out.print(xml.izpisiRacuneStranke("Bostjan"));
		System.out.print(xml.izpisiRacunStranke("Bostjan",1));
	
		xml.writeXML("d:\\baza.xml");
		
		//XMLBuild xml2 = new XMLBuild("d:\\baza.xml");

	}
	
	protected static String buildXML(Document doc){
		String s = "";
		try{
			DOMSource domSource= new DOMSource(doc);
			StringWriter writer= new StringWriter();
			StreamResult result= new StreamResult(writer);
			TransformerFactory tf= TransformerFactory.newInstance();
			Transformer transformer= tf.newTransformer();
			transformer.transform(domSource, result);
			s = writer.toString();
		}
		catch (TransformerConfigurationException e) {
			// TODO: handle exception
		}
		catch (TransformerException e) {
			// TODO: handle exception
		}
		return s;
	}
	
}
